/**
 * @file ProductList.jsx
 * @description 商品列表展示和筛选组件，包含搜索功能。
 */
import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css';
import { addItem } from '../store/cartSlice';
import { addItemToWishlist, removeItemFromWishlist } from '../store/wishlistSlice';
import toast from 'react-hot-toast';
import { fetchProducts } from '../services/api'; // 移除了 fetchProductsByCategory 因为在当前代码中未被使用
import { FaCartPlus, FaHeart, FaRegHeart, FaSearch } from 'react-icons/fa';

/**
 * @description 加载状态下的骨架屏组件
 * @returns {JSX.Element} Loading Skeleton UI
 */
const LoadingSkeleton = () => { // 重命名以避免与 ProductList 内部的 loading 状态变量混淆
  return (
    <>
      <div className="col-12 py-5 text-center">
        <Skeleton height={40} width={560} />
      </div>
      {[...Array(6)].map((_, index) => (
        <div className="col-md-4 col-sm-6 col-xs-8 col-12 mb-4" key={`skeleton-${index}`}>
          <Skeleton height={300} />
          <Skeleton height={20} style={{ marginTop: 10 }} />
          <Skeleton height={40} style={{ marginTop: 10 }} />
          <div className="mt-2">
              <Skeleton height={40} width={100} style={{ marginRight: 10 }} inline />
              <Skeleton height={40} width={120} inline />
          </div>
        </div>
      ))}
    </>
  );
};

/**
 * @description 展示商品列表及筛选、搜索功能的组件
 * @param {object} props - 组件属性
 * @param {Array<object>} props.filteredProducts - 经过筛选和搜索后的商品数据
 * @param {Array<object>} props.wishlistItems - 心愿单中的商品项
 * @param {string} props.currentCategory - 当前选中的商品分类
 * @param {string} props.searchTerm - 当前的搜索关键词
 * @param {Function} props.handleSearchChange - 搜索框内容变化的处理函数
 * @param {Function} props.handleCategoryFilter - 分类筛选按钮点击处理函数
 * @param {Function} props.handleToggleWishlist - 添加/移除心愿单商品的处理函数
 * @param {Function} props.handleAddItemToCart - 添加商品到购物车的处理函数
 * @returns {JSX.Element} Products display UI
 */
const ShowProductsComponent = React.memo(({ // 使用 React.memo 进一步优化
  filteredProducts,
  wishlistItems,
  currentCategory,
  searchTerm,
  handleSearchChange,
  handleCategoryFilter,
  handleToggleWishlist,
  handleAddItemToCart
}) => {
  return (
    <>
      <div className="col-12 mb-4">
        <div className="input-group">
          <span className="input-group-text" id="search-addon-stable"><FaSearch /></span> {/* 建议为 id 使用更稳定的名称 */}
          <input
            type="text"
            className="form-control form-control-lg"
            placeholder="搜索商品名称、描述或分类..."
            aria-label="搜索商品"
            aria-describedby="search-addon-stable"
            value={searchTerm}
            onChange={handleSearchChange}
          />
        </div>
      </div>

      <div className="col-12 buttons text-center py-4">
        <button className={`btn btn-sm m-2 ${currentCategory === 'all' ? 'btn-dark' : 'btn-outline-dark'}`} onClick={() => handleCategoryFilter('all')}>全部</button>
        <button className={`btn btn-sm m-2 ${currentCategory === "men's clothing" ? 'btn-dark' : 'btn-outline-dark'}`} onClick={() => handleCategoryFilter("men's clothing")}>男装</button>
        <button className={`btn btn-sm m-2 ${currentCategory === "women's clothing" ? 'btn-dark' : 'btn-outline-dark'}`} onClick={() => handleCategoryFilter("women's clothing")}>女装</button>
        <button className={`btn btn-sm m-2 ${currentCategory === "jewelery" ? 'btn-dark' : 'btn-outline-dark'}`} onClick={() => handleCategoryFilter("jewelery")}>珠宝</button>
        <button className={`btn btn-sm m-2 ${currentCategory === "electronics" ? 'btn-dark' : 'btn-outline-dark'}`} onClick={() => handleCategoryFilter("electronics")}>电子产品</button>
      </div>

      {filteredProducts.length > 0 ? filteredProducts.map((product) => {
          const isInWishlist = wishlistItems.some(item => item.id === product.id);
          return (
            <div key={product.id} className="col-md-4 col-sm-6 col-12 mb-4">
              <div className="card text-center h-100 shadow-sm">
                <div className="position-relative">
                    <Link to={`/product/${product.id}`} className="text-decoration-none text-dark d-block">
                        <img
                        src={product.image}
                        className="card-img-top p-3"
                        alt={product.title}
                        style={{ height: '250px', objectFit: 'contain' }}
                        />
                    </Link>
                    <button
                        className="btn btn-sm position-absolute top-0 end-0 m-2 p-1"
                        onClick={() => handleToggleWishlist(product)}
                        aria-label={isInWishlist ? "从心愿单移除" : "添加到心愿单"}
                        style={{ backgroundColor: 'rgba(255,255,255,0.8)', borderRadius: '50%', zIndex: 10, lineHeight: 1 }}
                        title={isInWishlist ? "从心愿单移除" : "添加到心愿单"}
                    >
                        {isInWishlist ? <FaHeart className="text-danger fs-5" /> : <FaRegHeart className="text-danger fs-5"/>}
                    </button>
                </div>
                <Link to={`/product/${product.id}`} className="text-decoration-none text-dark">
                    <div className="card-body d-flex flex-column">
                    <h5 className="card-title fs-6" style={{ minHeight: '3em' }}>
                        {product.title.substring(0, 35)}{product.title.length > 35 ? '...' : ''}
                    </h5>
                    <p className="card-text lead fw-bold mt-auto mb-2">${product.price.toFixed(2)}</p>
                    </div>
                </Link>
                <div className="card-footer bg-transparent border-top-0 pb-3">
                  <Link to={`/product/${product.id}`} className="btn btn-outline-dark m-1 btn-sm">
                    查看详情
                  </Link>
                  <button className="btn btn-dark m-1 btn-sm" onClick={() => handleAddItemToCart(product)}>
                    <FaCartPlus className="me-1" />
                    添加到购物车
                  </button>
                </div>
              </div>
            </div>
          );
        }) : (
          <div className="col-12 text-center py-5">
            <p className="lead">没有找到符合条件的商品。</p>
          </div>
        )}
    </>
  );
});
ShowProductsComponent.displayName = 'ShowProductsComponent'; // 为 React DevTools 设置显示名称

const ProductList = () => {
  const [allProductsData, setAllProductsData] = useState([]);
  const [filteredProducts, setFilteredProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentCategory, setCurrentCategory] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const dispatch = useDispatch();
  const wishlistItems = useSelector((state) => state.wishlist.items);

  useEffect(() => {
    let componentMounted = true;
    const getProducts = async () => {
      setLoading(true);
      try {
        const responseData = await fetchProducts();
        if (componentMounted && responseData) {
          setAllProductsData(responseData);
          setFilteredProducts(responseData); // 初始化时也设置 filteredProducts
        } else if (componentMounted && !responseData) {
            toast.error("无法加载商品数据。");
        }
      } catch (error) {
        if (componentMounted) {
          toast.error("获取商品时发生错误。");
        }
      } finally {
        if (componentMounted) {
          setLoading(false);
        }
      }
    };

    getProducts();

    return () => {
      componentMounted = false;
    };
  }, []);

  useEffect(() => {
    let productsToDisplay = allProductsData;

    if (currentCategory !== 'all') {
      productsToDisplay = productsToDisplay.filter(product => product.category === currentCategory);
    }

    if (searchTerm.trim() !== '') {
      const lowercasedSearchTerm = searchTerm.toLowerCase();
      productsToDisplay = productsToDisplay.filter(product =>
        product.title.toLowerCase().includes(lowercasedSearchTerm) ||
        (product.description && product.description.toLowerCase().includes(lowercasedSearchTerm)) || // 确保 description 存在
        (product.category && product.category.toLowerCase().includes(lowercasedSearchTerm)) // 确保 category 存在
      );
    }
    setFilteredProducts(productsToDisplay);
  }, [allProductsData, currentCategory, searchTerm]);


  const handleAddItemToCart = (product) => {
    if (product && product.id) {
      dispatch(addItem(product));
      toast.success(`${product.title ? product.title.substring(0,20) : '商品'}... 已添加到购物车!`);
    } else {
      toast.error("无法添加此商品到购物车。");
    }
  };

  const handleToggleWishlist = (product) => {
    if (!product || !product.id) {
      toast.error("操作心愿单商品失败。");
      return;
    }
    const isInWishlist = wishlistItems.some(item => item.id === product.id);
    if (isInWishlist) {
      dispatch(removeItemFromWishlist(product.id));
      // toast.success(`${product.title ? product.title.substring(0,20) : '商品'}... 已从心愿单移除!`); // 可选的提示
    } else {
      dispatch(addItemToWishlist(product));
      // toast.success(`${product.title ? product.title.substring(0,20) : '商品'}... 已添加到心愿单!`); // 可选的提示
    }
  };

  // handleSearchChange 保持不变，useCallback 是正确的
  const handleSearchChange = useCallback((event) => {
    setSearchTerm(event.target.value);
  }, []);

  const handleCategoryFilter = useCallback((category) => { // 对此也使用 useCallback，如果 ShowProductsComponent 未被 memo 包裹，这会有帮助
    setCurrentCategory(category);
  }, []);

  return (
    <div className="container my-3 py-3">
      <div className="row">
        <div className="col-12">
          <h2 className="display-5 text-center">最新商品</h2>
          <hr />
        </div>
      </div>
      <div className="row justify-content-center">
        {loading ? <LoadingSkeleton /> : (
          <ShowProductsComponent
            filteredProducts={filteredProducts}
            wishlistItems={wishlistItems}
            currentCategory={currentCategory}
            searchTerm={searchTerm}
            handleSearchChange={handleSearchChange}
            handleCategoryFilter={handleCategoryFilter}
            handleToggleWishlist={handleToggleWishlist}
            handleAddItemToCart={handleAddItemToCart}
          />
        )}
      </div>
    </div>
  );
};

export default ProductList;